#! /bin/sh -e

### BEGIN INIT INFO
# Provides:          sysfsconf
# Required-Start:    mountkernfs
# Should-Start:      udev module-init-tools cpufrequtils
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Set sysfs variables from /etc/sysfs.conf
# Description:       Similarly to /etc/init.d/procps.sh, you can configure
#                    values for sysfs variables (such as power management
#                    defaults) and /sys file permissions in /etc/sysfs.conf.
### END INIT INFO

# /etc/init.d/sysfsutils: 
#
# (c) 2005 Martin Pitt <mpitt@debian.org>

CONFFILE=/etc/sysfs.conf
CONFDIR=/etc/sysfs.d

[ -r "$CONFFILE" ] || exit 0
[ -d "$CONFDIR" ] || mkdir -p $CONFIR

. /lib/lsb/init-functions

load_conffile() {
    FILE="$1"
    sed  's/#.*$//; /^[[:space:]]*$/d; 
          s/^[[:space:]]*\([^=[:space:]]*\)[[:space:]]*\([^=[:space:]]*\)[[:space:]]*=[[:space:]]*\(.*\)/\1 \2 \3/' \
          $FILE | {
        while read f1 f2 f3; do
            if [ "$f1" = "mode" -a -n "$f2" -a -n "$f3" ]; then
                if [ -f "/sys/$f2" ]; then
                    chmod "$f3" "/sys/$f2"
                else
                    log_failure_msg "unknown attribute $f2"
                fi
            elif [ "$f1" = "owner" -a -n "$f2" -a -n "$f3" ]; then
                if [ -f "/sys/$f2" ]; then
                    chown "$f3" "/sys/$f2"
                else
                    log_failure_msg "unknown attribute $f2"
                fi
            elif [ "$f1" -a -n "$f2" -a -z "$f3" ]; then
                if [ -f "/sys/$f1" ]; then
                    # Some fields need a terminating newline, others
                    # need the terminating newline to be absent :-(
                     echo -n "$f2" > "/sys/$f1" 2>/dev/null ||
                        echo "$f2" > "/sys/$f1"
                else
                    log_failure_msg "unknown attribute $f1"
                fi
            else
                log_failure_msg "syntax error in $CONFFILE: '$f1' '$f2' '$f3'"
                log_end_msg 1
                exit 1
            fi
        done
    }
}	   



case "$1" in
    start|restart|force-reload)
	log_begin_msg "Setting sysfs variables..."
        for file in $CONFFILE $CONFDIR/*.conf; do
            [ -r "$file" ] || continue
            load_conffile "$file"
        done
	log_end_msg 0
	;;
    stop)
	;;
    *)
	echo "Usage: /etc/init.d/sysfsutils {start|stop|force-reload|restart}"
	exit 1
	;;
esac


